package com.example.yoga.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yoga.entity.*;
import com.example.yoga.service.ICardCourseService;
import com.example.yoga.service.ICoursePriceService;
import com.example.yoga.service.ICourseService;
import com.example.yoga.service.IUserCardService;
import com.example.yoga.util.JsonResult;
import com.example.yoga.util.PageDataResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liwenkai
 * @since 2021-02-19
 */
@RestController
@RequestMapping("/course")
public class CourseController {


    @Autowired
    private ICourseService courseService;

    @Autowired
    private IUserCardService userCardService;

    @Autowired
    private ICardCourseService cardCourseService;

    @Autowired
    private ICoursePriceService coursePriceService;


    /**
     * 获取系统内的用户总数
     */
    @RequestMapping(value = "/getTotalCourse",method = RequestMethod.GET)
    public JsonResult<Integer> getTotalCourse(){
        int totalCourse = courseService.getTotalCourse();
        return new JsonResult<>(2000,totalCourse);
    }



    /**
     * 添加课程
     */
    @RequestMapping("/addCourse")
    public JsonResult<Void> addCourse(@RequestBody CourseVo courseVo){
        if (courseVo.getCoursename()==null||courseVo.getCoursename().length()==0){
            return new JsonResult<>(4000,"课程名不为空！");
        }
        if (courseVo.getCoursemax()==null||courseVo.getCoursemax().length()==0){
            return new JsonResult<>(4000,"请规定最大课程人数！");
        }
        if (courseVo.getIsPrivate()==null||courseVo.getIsPrivate().length()==0){
            return new JsonResult<>(4000,"请选择课程性质！");
        }
        //重名验证
        QueryWrapper<Course> courseQueryWrapper1 = new QueryWrapper<>();
        courseQueryWrapper1.eq("courseName",courseVo.getCoursename());
        Course one1 = courseService.getOne(courseQueryWrapper1);
        if (one1!=null){
            return new JsonResult<>(4000,"课程名已存在！");
        }
        //添加课程并添加定价
        Course course = new Course();
        course.setCoursename(courseVo.getCoursename());
        course.setCoursemax(courseVo.getCoursemax());
        course.setIsPrivate(courseVo.getIsPrivate());
        System.out.println(courseVo.toString());
        boolean b = courseService.save(course);
        if (b){
            //找到这个courseId，并进行添加定价（前面增加了不重名验证，所以可以根据课程名进行添加）
            QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
            courseQueryWrapper.eq("courseName",courseVo.getCoursename());
            Course one = courseService.getOne(courseQueryWrapper);
            //将id和定价添加到数据表
            CoursePrice coursePrice = new CoursePrice();
            coursePrice.setCourseid(one.getCourseid());
            coursePrice.setCourseprice(Double.parseDouble(courseVo.getPrice()));
            coursePriceService.save(coursePrice);
            return new JsonResult<>(2000,"添加成功！");
        }else{
            return new JsonResult<>(4000,"添加失败！");
        }
    }

    /**
     * 下拉菜单，所有课程 getAllCourse
     */
    @RequestMapping("/getAllCourse")
    public JsonResult<List> getAllCourse(){
        List<Course> courseList = courseService.list();
        if (courseList.size()>0){
            return new JsonResult<>(2000,courseList) ;
        }else{
            return new JsonResult<>(4000,"没有课程") ;
        }
    }


    /**
     * 查询所有课程
     */
    @RequestMapping("/getCourseList")
    public PageDataResult getCourseList(String name, Integer pageIndex, Integer pageSize){
        PageHelper.startPage(pageIndex,pageSize);
        if (name==null||name.length()==0){
            //查询全部课程
            List<Course> list = courseService.list();
            PageInfo<Course> pageInfo = new PageInfo<Course>(list);
            PageDataResult pdr = new PageDataResult();
            pdr.setList(pageInfo.getList());
            pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
            return pdr;
        }
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.like("courseName",name);
        List<Course> list = courseService.list(wrapper);
        //进行分页
        PageInfo<Course> pageInfo = new PageInfo<Course>(list);
        PageDataResult pdr = new PageDataResult();
        pdr.setList(pageInfo.getList());
        pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
        return pdr;
    }

    /**
     * 根据id修改课程
     */
    @RequestMapping(value = "/updateCourseById",method = RequestMethod.PUT)
    public JsonResult<Void> updateCourseById(@RequestBody Course course) {
        System.out.println(course.toString()+"************************");
        Integer courseid = course.getCourseid();
        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.eq("courseId",courseid);
        boolean b = courseService.update(course, courseQueryWrapper);
        if (b){
            return new JsonResult<>(2000,"修改成功");
        }
        return new JsonResult<>(4000,"修改失败");
    }


    /**
     * 删除课程
     */
    @RequestMapping(value="/delCourse",method = RequestMethod.DELETE)
    public JsonResult<Void> delCourse(Integer id) {
        //在删除课程之前，判断是否有用户还在该课程下
        QueryWrapper<CardCourse> cardCourseQueryWrapper = new QueryWrapper<>();
        cardCourseQueryWrapper.eq("courseId",id);
        cardCourseQueryWrapper.isNotNull("buyDate");
        List<CardCourse> list = cardCourseService.list(cardCourseQueryWrapper);
        if(list.size()>0){
            return new JsonResult<>(4000,"该课程下尚有用户，不能删除！");
        }
        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.eq("courseId",id);
        boolean b = courseService.remove(courseQueryWrapper);
        if (b){
            return new JsonResult<>(2000,"删除成功");
        }
        return new JsonResult<>(4000,"删除失败");
    }


    /**
     * 批量删除用户
     */
    @PostMapping("/delByIds")
    public JsonResult<Void> delByIds(@RequestBody List<Integer> ids){
        if (!ObjectUtils.isEmpty(ids)){
            //为了减少数据库连接，取出所有的mvcourse关系表
            QueryWrapper<CardCourse> cardCourseQueryWrapper = new QueryWrapper<>();
            cardCourseQueryWrapper.isNotNull("buyDate");
            List<CardCourse> list = cardCourseService.list(cardCourseQueryWrapper);
            //遍历这个list,逐一比较
            for (int i = 0; i < list.size(); i++) {
                for (int j = 0; j < ids.size(); j++) {
                    if(ids.get(j).equals(list.get(i).getCourseid())){
                        return new JsonResult<>(3000,"您选择的课程中存在正在使用中的课程，不能删除");
                    }
                }
            }
            courseService.removeByIds(ids);
            return new JsonResult<>(2000,"删除成功");
        }
        return new JsonResult<>(4000,"请选择要删除的课程！");
    }


    /**
     * 获取教练所带课程
     */
    @RequestMapping("/getTeaCourseList")
    public PageDataResult getTeaCourseList(String userid, Integer pageIndex, Integer pageSize){
        PageHelper.startPage(pageIndex,pageSize);
        //获取我的课程的列表
        //根据userid找到cardid
        QueryWrapper<UserCard> wrapper = new QueryWrapper<>();
        wrapper.eq("userId",userid);
        UserCard one = userCardService.getOne(wrapper);
        if(one==null){
            PageDataResult pdr = new PageDataResult();
            return null;
        }
        //找到cardid之后.再根据cardid找到该教练所带的所有课程
        QueryWrapper<CardCourse> cardCourseQueryWrapper = new QueryWrapper<>();
        cardCourseQueryWrapper.eq("cardId",one.getCardid());
        List<CardCourse> list = cardCourseService.list(cardCourseQueryWrapper);
        List list1=new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            list1.add(list.get(i).getCourseid());
        }
        //获取到所有的课程id列表,找出课程名
        List<Course> courseList = courseService.listByIds(list1);
        if (courseList.size()>0){
            PageInfo<Course> pageInfo = new PageInfo<>(courseList);
            PageDataResult pdr = new PageDataResult();
            pdr.setList(pageInfo.getList());
            pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
            return pdr;
        }
        return null;
    }

}

